#include "WinExHandler.h"
#include <string>
#include <eh.h>

using namespace std;

namespace helix
{

	void Win32ExceptionHandler::installHandler()
	{
		//Make sure the already installed translator is not this one
	//	if(Win32Exception::prevHandler != Win32Exception::translate)
	//		Win32Exception::prevHandler = _set_se_translator(Win32Exception::translate);
		_set_se_translator(translate);
	}

	void Win32ExceptionHandler::uninstallHandler()
	{
	//	_set_se_translator(prevHandler);
		_set_se_translator(NULL);
	}

	void Win32ExceptionHandler::translate(unsigned code, EXCEPTION_POINTERS* info)
	{
		switch (code) {
		case EXCEPTION_ACCESS_VIOLATION:
			throw AccessViolationException(*(info->ExceptionRecord));
			break;
		default:
			throw Win32Exception(*(info->ExceptionRecord));
		}
	}

	Win32Exception::Win32Exception(const EXCEPTION_RECORD& info)
	{
		exType = "Win32Exception";
		location = info.ExceptionAddress;
		exCode = info.ExceptionCode;
	}

	AccessViolationException::AccessViolationException(const EXCEPTION_RECORD& info)
	: Win32Exception(info)
	{
		exType = "AccessViolationException";
		writeViolation = info.ExceptionInformation[0] == 1;
		badAddress = reinterpret_cast<Address>(info.ExceptionInformation[1]);
	}

}